package com.muzi.onvif.onvif.util;

import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ImgUtils {
    /**
     * *
     * @param urlString 图片url
     * @param localUrl 本地图片路径
     * @param name 图片名称
     * @throws Exception
     */
    public static void download(String urlString,String username, String password) throws Exception {

        // 账号密码base64编码(海康)
        String userPassword = username + ":" + password;
        String encoding = Base64.encodeBase64String(userPassword.getBytes());
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        con.setRequestProperty("Authorization", "Basic " + encoding);
        // 格式化时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HHmmssSSS");
        String format = simpleDateFormat.format(new Date());
        // 输出的文件流
        String path = "D:\\words\\yszt-pgsql\\img";
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        String filename = path + "/" + format + ".jpg";
        File file = new File(filename);
        // 1k的缓冲数据
        byte[] bs = new byte[1024];
        // 阅读到的数据长度
        int len;
        // 获取输入流
        InputStream inputStream = con.getInputStream();
        // 开始读取
        FileOutputStream outputStream = new FileOutputStream(file, true);
        while ((len = inputStream.read(bs)) != -1) {
            outputStream.write(bs, 0, len);
        }
        inputStream.close();
        outputStream.close();


    }

    // 使用HTTP客户端下载文件的方法
    public static void downloadFile(String fileUrl, File destination) throws IOException {
        // 这里可以使用HttpURLConnection或Apache HttpClient等库来下载文件
        // 以下是一个使用HttpURLConnection的示例
        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 总是检查HTTP响应码是否为HTTP_OK
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = httpConn.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(destination);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();
            System.out.println("文件下载完成");
        } else {
            System.out.println("无法下载文件: HTTP响应码为 " + responseCode);
        }
        httpConn.disconnect();
    }
}
